package CanvaWeb.CanvaWeb.Controller;

import CanvaWeb.CanvaWeb.Repository.RoomRepository;
import CanvaWeb.CanvaWeb.Service.ChatMessageService;
import CanvaWeb.CanvaWeb.pojo.ChatMessage;
import CanvaWeb.CanvaWeb.pojo.SendMessageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.logging.Logger;
import java.util.List;

@RestController
@RequestMapping("/room/{roomId}/messages")
public class ChatMessageController {

    @Autowired
    private ChatMessageService chatMessageService;

    @Autowired
    private RoomRepository roomRepository;  // 用于验证房间存在

    private static final Logger logger = Logger.getLogger(ChatMessageController.class.getName());

    // 发送消息
    @PostMapping
    public ResponseEntity<?> sendMessage(@RequestBody SendMessageRequest request) {

        Long roomId = request.getRoomId();
        Long userId = request.getUserId();
        String message = request.getMessage();

        logger.info("收到发送消息请求: roomId = " + roomId + ", userId = " + userId + ", message = " + message);

        // 校验房间 ID 和用户 ID
        if (roomId == null || roomId <= 0 || !roomRepository.existsById(roomId)) {
            logger.warning("无效的房间ID: " + roomId);
            return ResponseEntity.badRequest().body("无效的房间ID！");
        }

        if (userId == null || userId <= 0) {
            logger.warning("无效的用户ID: " + userId);
            return ResponseEntity.badRequest().body("无效的用户ID！");
        }

        if (message == null || message.trim().isEmpty()) {
            logger.warning("消息内容为空！");
            return ResponseEntity.badRequest().body("消息内容不能为空！");
        }

        // 限制消息长度
        if (message.length() > 500) {
            logger.warning("消息内容超过500个字符: " + message.length());
            return ResponseEntity.badRequest().body("消息内容不能超过500个字符！");
        }

        // 发送消息
        try {
            // 调用服务层的 sendMessage 方法保存消息
            ChatMessage savedMessage = chatMessageService.sendMessage(roomId, userId, message);

            // 返回成功响应
            logger.info("消息发送成功: " + savedMessage);
            return ResponseEntity.ok(savedMessage);
        } catch (RuntimeException e) {
            logger.severe("发送消息失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("发送消息失败：" + e.getMessage());
        }
    }



    // 获取消息（历史消息）
    @GetMapping
    public ResponseEntity<?> getMessages(
            @PathVariable Long roomId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "20") int size) {

        // 校验 roomId 是否有效
        if (roomId <= 0 || !roomRepository.existsById(roomId)) {
            return ResponseEntity.badRequest().body("无效的房间ID！");
        }

        try {
            // 获取房间的历史消息
            List<ChatMessage> messages = chatMessageService.getMessages(roomId, page, size);
            return ResponseEntity.ok(messages);
        } catch (RuntimeException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("获取消息失败：" + e.getMessage());
        }
    }
}





